

#include "commonlutwidget.h"
#include "ui_CommonLutWidget.h"


CommonLutWidget::CommonLutWidget(QWidget *parent) :
    QWidget(parent), ui(new Ui::CommonLutWidget) {
    ui->setupUi(this);
}

CommonLutWidget::~CommonLutWidget() {
    delete ui;
}

void CommonLutWidget::initLUTWidget(QWidget* parentWidget) {
    if (!parentWidget) {
        qWarning() << "Parent widget is not initialized!";
        return;
    }

    m_lutLabel = new QLabel(parentWidget);
    m_lutLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    m_lutLabel->setAlignment(Qt::AlignCenter);

    // 初始化刻度标签
    QFont scaleFont;
    scaleFont.setPointSize(7);
    for (int i = 0; i < 6; ++i) {
        QLabel* scaleLabel = new QLabel(parentWidget);
        scaleLabel->setFont(scaleFont);
        scaleLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
        scaleLabel->setStyleSheet("color: white;");
        scaleLabel->setText(QString::number(i * 0.2, 'f', 1));
        m_scaleLabels.append(scaleLabel);
    }
}

void CommonLutWidget::updateLUTDisplay(QWidget* parentWidget) {
    if (!m_lutLabel || !parentWidget) return;

    int width = parentWidget->width();
    if (width < 50) width = 53;
    int height = parentWidget->height();

 //   qDebug() << "width:" << width << "height:" << height;

    int lutWidth = width * 0.6;
    int scaleWidth = width - lutWidth;

    int lutHeight = height - 10;
    int lutTopMargin = 5;

    m_lutLabel->setGeometry(0, lutTopMargin, lutWidth, lutHeight);

    // 调整刻度标签的位置
    for (int i = 0; i < 6; ++i) {
        double value = i * 0.2;
        int yPos;

        if (i == 0) {
            yPos = height - lutTopMargin - (i * (lutHeight / 5.0)) - 2;
        } else if (i == 5) {
            yPos = height - lutTopMargin - (i * (lutHeight / 5.0)) + 2;
        } else {
            yPos = height - lutTopMargin - (i * (lutHeight / 5.0));
        }

        QLabel* scaleLabel = m_scaleLabels[i];
        if (i == 0 || i == 5) {
            scaleLabel->setText(QString("-%1").arg(QString::number(value, 'f', 0)));
            scaleLabel->setGeometry(lutWidth - 2, yPos - 10, scaleWidth, 20);
        } else {
            scaleLabel->setText(QString("-%1").arg(QString::number(value, 'f', 1)));
            scaleLabel->setGeometry(lutWidth + 3, yPos - 10, scaleWidth, 20);
        }
    }

    // 绘制 LUT
    QImage lutImage(1, 256, QImage::Format_RGB32);
    for (int y = 0; y < 256; ++y) {
        BYTE r = RayCiLut::LUT[y][0];
        BYTE g = RayCiLut::LUT[y][1];
        BYTE b = RayCiLut::LUT[y][2];
        lutImage.setPixelColor(0, 255 - y, QColor(r, g, b));
    }

    QPixmap pixmap = QPixmap::fromImage(lutImage)
        .scaled(lutWidth, lutHeight, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    m_lutLabel->setPixmap(pixmap);
}
